package com.xiaozhen.cmdb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaozhen.cmdb.dao.CmdbExampleDao;
import com.xiaozhen.cmdb.dao.CmdbExampleValueDao;
import com.xiaozhen.cmdb.service.CmdbExampleService;
import com.xiaozhen.common.core.domain.cmdb.CmdbExample;
import com.xiaozhen.common.core.domain.cmdb.CmdbExampleValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/9 14:25
 * @description:
 */
@Service
public class CmdbExampleServiceImpl implements CmdbExampleService {

    @Autowired
    private CmdbExampleDao cmdbExampleDao;
    @Autowired
    private CmdbExampleValueDao cmdbExampleValueDao;

    @Override
    public List<CmdbExample> selectCmdbExampleList() {
        List<CmdbExample> exampleList = cmdbExampleDao.selectByMap(new HashMap<>(8));
        for (CmdbExample cmdbExample : exampleList) {
            QueryWrapper<CmdbExampleValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("example_id", cmdbExample.getExampleId());
            List<CmdbExampleValue> exampleValues = cmdbExampleValueDao.selectList(queryWrapper);
            cmdbExample.setExampleValues(exampleValues);
        }
        return exampleList;
    }

    @Override
    public Integer insertCmdbExample(CmdbExample cmdbExample) {
        return cmdbExampleDao.insert(cmdbExample);
    }

    @Override
    public Integer updateCmdbExample(CmdbExample cmdbExample) {
        int count = cmdbExampleDao.updateById(cmdbExample);
        if (count > 0) {
            QueryWrapper<CmdbExampleValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("example_id", cmdbExample.getExampleId());
            cmdbExampleValueDao.delete(queryWrapper);
        }
        return count;
    }

    @Override
    public Integer deleteExampleById(Long exampleId) {
        int count = cmdbExampleDao.deleteById(exampleId);
        if (count > 0) {
            QueryWrapper<CmdbExampleValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("example_id", exampleId);
            cmdbExampleValueDao.delete(queryWrapper);
        }
        return count;
    }
}
